<?php

namespace App\Repository\Sys;


class JsonRespose
{

    //response 成功返回
    static public function success($data = array(), $msg = '操作成功!', $code = 1)
    {
        $response = array(
            'code' => $code,
            'msg' => $msg,
            'data' => json_decode(json_encode($data), true)
        );
        $response = self::PregNull($response);
        return response()->json($response, 200, ['Content-Type' => 'application/json;charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }


    //response 失败返回
    static public function fail($msg = '操作失败!', $code = 0)
    {
        $response = array(
            'code' => $code,
            'msg' => $msg,
        );
        \Log::notice($_SERVER['REQUEST_URI'] . "\n" . json_encode($response, JSON_UNESCAPED_UNICODE));
        return response()->json($response, 200, ['Content-Type' => 'application/json;charset=utf-8'], JSON_UNESCAPED_UNICODE);

    }


    //内部接口返回
    static public function jsonArray($code = 0, $data = array(), $msg = null)
    {

        return array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
    }

    //内部接口response返回
    static public function done($jsonArray)
    {
        if ($jsonArray['code'] == 1) {
            if (is_null($jsonArray['msg'])) {
                $jsonArray['msg'] = '操作成功!';
            }

            return self::success($jsonArray['data'], $jsonArray['msg'], $jsonArray['code']);
        } else {
            if (is_null($jsonArray['msg'])) {
                $jsonArray['msg'] = '操作失败';
            }
            unset($jsonArray['data']);
            return self::fail($jsonArray['msg'], $jsonArray['code']);
        }
    }


    /**
     * 转换数组里面的null为空字符串
     * @param $v
     * @return array
     *
     */
    private static function PregNull(&$v)
    {
        if (is_array($v)) {
            foreach ($v as $k => $a) {
                if (gettype($a) == 'array') {
                    $v[$k] = self::PregNull($v[$k]);
                } else if ($a === null) {
                    $v[$k] = '';
                }
            }
            return $v;
        }
        return $v;
    }


}
